package com.mls.fivedistrict.server.impl;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mls.fivedistrict.dao.GoodsOrderMapper;
import com.mls.fivedistrict.entity.request.AwardRequest;
import com.mls.fivedistrict.entity.request.CreateOrderRequest;
import com.mls.fivedistrict.entity.request.PayOrderRequest;
import com.mls.fivedistrict.entity.request.TransferAccountRequest;
import com.mls.fivedistrict.entity.response.CreateOrderResponse;
import com.mls.fivedistrict.enums.GoodsOrderStatusEnum;
import com.mls.fivedistrict.enums.RecordProductTypeEnum;
import com.mls.fivedistrict.enums.RecordStatusEnum;
import com.mls.fivedistrict.exception.CustomerException;
import com.mls.fivedistrict.pojo.*;
import com.mls.fivedistrict.server.*;
import com.mls.fivedistrict.util.SnowflakeIdWorker;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Five Team
 * @since 2018-05-15
 */
@Slf4j
@Service
public class GoodsOrderServiceImpl extends ServiceImpl<GoodsOrderMapper, GoodsOrder> implements GoodsOrderService {
    @Autowired
    GoodsService goodsService;

    @Autowired
    IntegralService integralService;

    @Autowired
    PropertyService propertyService;

    @Autowired
    GoodsOrderPayIntegralService goodsOrderPayIntegralService;

    @Autowired
    GoodsPayIntegralService goodsPayIntegralService;

    @Autowired
    RecordService recordService;

    @Autowired
    AwardService awardService;

    @Autowired
    UserService userService;

    @Autowired
    SysSettingService sysSettingService;

    @Transactional
    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest createOrderRequest) {
        Goods goods = goodsService.selectById(createOrderRequest.getGoodsId());
        if (goods == null) {
            throw new CustomerException("商品不存在");
        }
        //查询用户是否满足兑换条件
        BigDecimal minDwqAbility = goods.getMinDwqAbility();
        Property dwqDetail = propertyService.getDWQDetail(createOrderRequest.getUserId());
        if (dwqDetail.getTotal().compareTo(minDwqAbility) <= 0) {
            throw new CustomerException("DWQ不足未满足条件");
        }
        if (goods.getGoodsType().equals("entity")) {
            Optional.ofNullable(createOrderRequest.getPhone()).orElseThrow(() -> new CustomerException("收货手机号不能为空"));
            Optional.ofNullable(createOrderRequest.getShippingAddress()).orElseThrow(() -> new CustomerException("收货地址不能为空"));
        }
        //生成订单号
        long orderNo = new SnowflakeIdWorker(0, 0).nextId();
        GoodsOrder goodsOrder = new GoodsOrder();
        goodsOrder.setGoodId(createOrderRequest.getGoodsId());
        goodsOrder.setUserId(createOrderRequest.getUserId());
        goodsOrder.setConsignee(createOrderRequest.getConsignee());
        goodsOrder.setOrderNo(orderNo + "");
        goodsOrder.setConsignee(createOrderRequest.getConsignee());
        goodsOrder.setPhone(createOrderRequest.getPhone());
        goodsOrder.setShippingAddress(createOrderRequest.getShippingAddress());
        goodsOrder.setStatus(GoodsOrderStatusEnum.UNPAID);
        boolean insert = insert(goodsOrder);
        if (!insert) {
            throw new CustomerException("订单创建失败");
        }
        //根据积分计算金额
        BigDecimal price = goods.getPrice();
        Integral integralDetail = integralService.getIntegralDetail(createOrderRequest.getIntegralId());
        if (integralDetail == null) {
            throw new CustomerException("积分不存在");
        }
        BigDecimal referPrice = integralDetail.getReferPrice();
        //实际需要支付积分数量为
        BigDecimal divide = price.divide(referPrice, 4, RoundingMode.UP);
        //计算返利比例
        GoodsPayIntegral goodsPayIntegral = goodsPayIntegralService.selectGoodsPayIntegralByIntegral(createOrderRequest.getGoodsId(), createOrderRequest.getIntegralId());
        if (goodsPayIntegral == null) {
            throw new CustomerException("商品支付方式不支持");
        }
        Double rebateRatio = goodsPayIntegral.getRebateRatio();
        BigDecimal rebateValue = divide.multiply(new BigDecimal(rebateRatio));

        GoodsOrderPayIntegral goodsOrderPayIntegral = new GoodsOrderPayIntegral();
        goodsOrderPayIntegral.setPayNumber(divide);
        goodsOrderPayIntegral.setGoodsPayIntegralId(createOrderRequest.getIntegralId());
        goodsOrderPayIntegral.setRebateNumber(rebateValue);
        goodsOrderPayIntegral.setOrderId(goodsOrder.getId());
        boolean goodsOrderPayIntegralInsert = goodsOrderPayIntegralService.insert(goodsOrderPayIntegral);
        if (!goodsOrderPayIntegralInsert) {
            throw new CustomerException("创建订单支付积分出错");
        }
        CreateOrderResponse createOrderResponse = new CreateOrderResponse();
        createOrderResponse.setOrderId(goodsOrder.getId());
        createOrderResponse.setRebateNumber(rebateValue);
        createOrderResponse.setOrderNo(orderNo);
        createOrderResponse.setPayNumber(divide);
        return createOrderResponse;
    }

    @Transactional
    @Override
    public boolean payOrder(PayOrderRequest payOrderRequest) {
        Wrapper wrapper = Condition.create();
        wrapper.eq("id", payOrderRequest.getOrderId());
        wrapper.eq("user_id", payOrderRequest.getUserId());
        GoodsOrder goodsOrder = selectOne(wrapper);
        if (goodsOrder == null) {
            throw new CustomerException("订单不存在");
        }
        if (!goodsOrder.getStatus().getValue().equals(GoodsOrderStatusEnum.UNPAID.getValue())) {
            throw new CustomerException("订单状态出错");
        }
        GoodsOrderPayIntegral goodsOrderPayIntegral = goodsOrderPayIntegralService.selectGoodsOrderPayIntegralByOrder(payOrderRequest.getOrderId());
        if (goodsOrderPayIntegral == null) {
            throw new CustomerException("订单支付积分不存在");
        }
        SysSetting sysSetting = sysSettingService.getSysSettingByKey("OfficialAccount");
        if (sysSetting == null || StringUtils.isEmpty(sysSetting.getSettingValue())) {
            throw new CustomerException("官方账号不存在");
        }
        User targetUser = userService.getUserByPhone(sysSetting.getSettingValue());
        if (targetUser == null) {
            throw new CustomerException("官方账号不存在");
        }

        //进行支付 减资产加资产 添加记录 奖励dwq 返现
        TransferAccountRequest transferAccountRequest = new TransferAccountRequest();
        transferAccountRequest.setIntegralId(goodsOrderPayIntegral.getGoodsPayIntegralId());
        transferAccountRequest.setUserId(payOrderRequest.getUserId());
        transferAccountRequest.setWalletPassword(payOrderRequest.getWalletPassword());
        transferAccountRequest.setValue(goodsOrderPayIntegral.getPayNumber());
        transferAccountRequest.setRemind("商品兑换");
        transferAccountRequest.setTargetUserId(targetUser.getId());

        userService.transferAsset(transferAccountRequest, RecordProductTypeEnum.COMMODITYEXCHANGE.getValue());
        //奖励DWQ
        Goods goods = goodsService.selectById(goodsOrder.getGoodId());
        if (goods.getRewardDwqNumber().compareTo(new BigDecimal(0)) > 0) {
            AwardRequest awardRequest = new AwardRequest();
            awardRequest.setTargetUserId(payOrderRequest.getUserId());
            awardRequest.setIntegralId(18L);
            awardRequest.setAwardNumber(goods.getRewardDwqNumber());
            awardRequest.setSource(RecordProductTypeEnum.CONTRIBUTION.getValue());
            awardRequest.setReason("商品兑换贡献值");
            awardService.awardDwq(awardRequest);

        }
        //返利
        TransferAccountRequest rebateTransferAccountRequest = new TransferAccountRequest();
        rebateTransferAccountRequest.setIntegralId(goodsOrderPayIntegral.getGoodsPayIntegralId());
        rebateTransferAccountRequest.setUserId(targetUser.getId());
        rebateTransferAccountRequest.setValue(goodsOrderPayIntegral.getRebateNumber());
        rebateTransferAccountRequest.setRemind("商品兑换返利");
        rebateTransferAccountRequest.setTargetUserId(payOrderRequest.getUserId());
        userService.transferAsset(transferAccountRequest, RecordProductTypeEnum.REBATE.getValue());
        //修改订单状态为支付成功
        GoodsOrder newGoodsOrder = new GoodsOrder();
        newGoodsOrder.setId(goodsOrder.getId());
        newGoodsOrder.setStatus(GoodsOrderStatusEnum.UNSHIPPED);
        newGoodsOrder.setVersion(goodsOrder.getVersion());
        boolean b = updateById(newGoodsOrder);
        if (!b) {
            throw new CustomerException("支付失败");
        }
        //减少库存
        Goods newGoods = new Goods();
        newGoods.setId(goods.getId());
        newGoods.setVersion(goods.getVersion());
        newGoods.setInventory(goods.getInventory() - 1);
        boolean b1 = goodsService.updateById(newGoods);
        if (!b1) {
            throw new CustomerException("扣减库存失败");
        }
        return true;
    }

    @Override
    public void cancelOrder(Long goodsOrderId, Long userId) {
        Wrapper wrapper = Condition.create();
        wrapper.eq("id", goodsOrderId);
        wrapper.eq("user_id", userId);
        GoodsOrder goodsOrder = selectOne(wrapper);
        if (goodsOrder == null) {
            throw new CustomerException("订单不存在");
        }
        if (!goodsOrder.getStatus().getValue().equals(GoodsOrderStatusEnum.UNPAID.getValue())) {
            throw new CustomerException("订单状态不对");
        }
        GoodsOrder newGoodsOrder = new GoodsOrder();
        newGoodsOrder.setId(goodsOrderId);
        newGoodsOrder.setStatus(GoodsOrderStatusEnum.EXPIRED);
        newGoodsOrder.setVersion(goodsOrder.getVersion());
        boolean b = updateById(newGoodsOrder);
        if (!b) {
            throw new CustomerException("取消失败");
        }
    }

    @Override
    public void autoCloseOrder() {
        long lastTime = new Date().getTime() - 30 * 60 * 1000;
        Wrapper wrapper = Condition.create();
        wrapper.eq("status", GoodsOrderStatusEnum.UNPAID.getValue());
        wrapper.le("create_date", new Date(lastTime));
        List<GoodsOrder> list = selectList(wrapper);
        List<GoodsOrder> goodsOrders = new ArrayList<>();
        for (GoodsOrder goodsOrder : list) {
            GoodsOrder newGoodsOrder = new GoodsOrder();
            newGoodsOrder.setId(goodsOrder.getId());
            newGoodsOrder.setVersion(goodsOrder.getVersion());
            newGoodsOrder.setStatus(GoodsOrderStatusEnum.EXPIRED);
            goodsOrders.add(newGoodsOrder);
        }
        if (goodsOrders.size() > 0) {
            boolean b = updateBatchById(goodsOrders);
            log.info("批量更新：{}", b);
        }


    }

}
